package com.programming.forum.services.impl;

import com.programming.forum.common.AppResult;
import com.programming.forum.common.ResultCode;
import com.programming.forum.dao.ArticleMapper;
import com.programming.forum.exception.ApplicationException;
import com.programming.forum.model.Article;
import com.programming.forum.model.Board;
import com.programming.forum.model.User;
import com.programming.forum.services.IArticleService;
import com.programming.forum.services.IBoardService;
import com.programming.forum.services.IUserService;
import com.programming.forum.utils.StringUtil;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 22479
 * Date: 2023-11-07
 * Time: 19:32
 */

/**
 * IArticleService 接口实现类
 * 帖子相关业务逻辑
 */
@Service
@Slf4j
public class ArticleServiceImpl implements IArticleService {

    @Resource
    private ArticleMapper articleMapper;

    //用户和版块的操作
    @Resource
    private IUserService userService;
    @Resource
    private IBoardService boardService;

    /**
     * 发布帖子 -- 涉及到三张表的操作 -- 启用事务操作
     * @param article
     */
    @Override
    public void create(Article article) {
        //非空校验
        if(article == null || article.getUserId() == null || article.getBoardId() == null
        || StringUtil.isEmpty(article.getTitle())
        || StringUtil.isEmpty(article.getContent())) {
            //FAILED_PARAMS_VALIDATE  (1002, "参数校验失败"),
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());

            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        //设置默认值
        article.setVisitCount(0); //访问数
        article.setReplyCount(0); //回复数
        article.setLikeCount(0); //点赞数
        article.setDeleteState((byte) 0);
        article.setState((byte) 0);
        Date date = new Date();
        article.setCreateTime(date);
        article.setUpdateTime(date);

        //写入数据库
        int row = articleMapper.insertSelective(article);
        if(row != 1) {
            // FAILED_CREATE           (1004, "新增失败"),
            log.warn(ResultCode.FAILED_CREATE .toString() );

            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE ));
        }
        //更新用户发帖数
        userService.addOneArticleCountById(article.getUserId());
        //更新版块发帖数
        boardService.addOneArticleCountById(article.getBoardId());

        //发帖操作完成
        log.info(ResultCode.SUCCESS.toString() + "," + "user Id = " + article.getUserId()
        + ", board id =" + article.getBoardId() + "发帖成功"  );


    }

    /**
     * 查询所有帖子
     * @return
     */
    @Override
    public List<Article> selectAll() {
        //调用DAO
        List<Article> articles = articleMapper.selectAll();
        //返回结果
        return articles;
    }

    /**
     * 根据板块Id查询帖子
     * @return
     */
    @Override
    public List<Article> selectByBoardId(Long boardId) {
        //非空校验
        if(boardId == null) {
            //FAILED_PARAMS_VALIDATE  (1002, "参数校验失败"),
            log.info(ResultCode.FAILED_PARAMS_VALIDATE.toString());

            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //校验板块是否存在
        Board board = boardService.selectById(boardId);
        if(board == null) {
            //FAILED_BOARD_BANNED      (1203,"版块状况异常, 请联系管理员."),
            log.info(ResultCode.FAILED_BOARD_BANNED  .toString());

            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_BOARD_BANNED  ));
        }
        //调用DAO
        List<Article> articles = articleMapper.selectByBoardId(boardId);
        //返回结果
        return articles;
    }

    /**
     * 根据文章Id查询帖子所有信息
     * @param id
     * @return 帖子详情
     */
    @Override
    public Article selectDetailById(Long id) {
        //非空校验
        if(id == null || id <= 0) {
            //FAILED_PARAMS_VALIDATE  (1002, "参数校验失败"),
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());

            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        Article article = articleMapper.selectDetailById(id);
        //判断结果是否为空
        if(article == null) {
            //FAILED_Article_NOT_EXISTS      (1301,"帖子不存在"),
            log.warn(ResultCode.FAILED_Article_NOT_EXISTS.toString());

            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_Article_NOT_EXISTS));
        }
        //文章访问次数 + 1
        Article updateArticle = new Article();
        updateArticle.setId(article.getId());
        updateArticle.setVisitCount(article.getVisitCount() + 1);
        //保存到数据库
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if(row != 1) {
            // ERROR_SERVICES          (2000, "服务器内部错误"),
            log.warn(ResultCode.ERROR_SERVICES.toString());

            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
        //更新返回对象的访问次数
        article.setVisitCount(article.getVisitCount() + 1);
        //返回帖子详情
        return article;
    }

    /**
     * 编辑文章
     * @param id 文章Id
     * @param title 文章标题
     * @param content   文章正文
     */
    @Override
    public void modify(Long id, String title, String content) {
        //非空校验
        if(id == null || id <= 0 || StringUtil.isEmpty(title) || StringUtil.isEmpty(content)) {
            //FAILED_PARAMS_VALIDATE  (1002, "参数校验失败"),
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());

            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        Article updateArticle = new Article();
        updateArticle.setId(id);
        updateArticle.setTitle(title);
        updateArticle.setContent(content);
        updateArticle.setUpdateTime(new Date());
        //调用更新SQL语句
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if(row != 1) {
            // ERROR_SERVICES          (2000, "服务器内部错误"),
            log.warn(ResultCode.ERROR_SERVICES.toString());

            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
    }

    @Override
    public Article selectById(Long id) {
        //非空校验
        if(id == null || id <= 0) {
            //FAILED_PARAMS_VALIDATE  (1002, "参数校验失败"),
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());

            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        Article article = articleMapper.selectByPrimaryKey(id);
        return article;
    }

    /**
     * 点赞
     * @param id
     */
    @Override
    public void thumbsUpById(Long id) {
        //非空校验
        if(id == null || id <= 0) {
            //FAILED_PARAMS_VALIDATE  (1002, "参数校验失败"),
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());

            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 获取帖子详情
        Article article = articleMapper.selectByPrimaryKey(id);
        // 帖子不存在
        if (article == null || article.getDeleteState() == 1) {
            // 打印日志  FAILED_NOT_EXISTS        (1005, "资源不存在"),
            log.warn(ResultCode. FAILED_NOT_EXISTS .toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode. FAILED_NOT_EXISTS ));
        }
        // 帖子状态异常
        if (article.getState() == 1) {
            // 打印日志  FAILED_FORBIDDEN        (1003, "禁止访问"),
            log.warn(ResultCode.FAILED_FORBIDDEN .toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_FORBIDDEN ));
        }

        // 构造要更新的对象
        Article updateArticle = new Article();
        updateArticle.setId(article.getId());
        updateArticle.setLikeCount(article.getLikeCount() + 1);

        // 调用DAO
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if (row != 1) {
            // 打印日志  ERROR_SERVICES          (2000, "服务器内部错误"),
            log.warn(ResultCode.ERROR_SERVICES.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }

    }

    /**
     * 删帖功能 根据Id删除帖子
     * @param id
     */
    @Override
    public void deleteById(Long id) {
        //非空校验
        if(id == null || id <= 0) {
            //FAILED_PARAMS_VALIDATE  (1002, "参数校验失败"),
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());

            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 获取帖子详情
        Article article = articleMapper.selectByPrimaryKey(id);
        // 帖子不存在
        if (article == null || article.getDeleteState() == 1) {
            // 打印日志  FAILED_NOT_EXISTS        (1005, "资源不存在"),
            log.warn(ResultCode. FAILED_NOT_EXISTS .toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode. FAILED_NOT_EXISTS ));
        }
        // 帖子状态异常
        if (article.getState() == 1) {
            // 打印日志  FAILED_FORBIDDEN        (1003, "禁止访问"),
            log.warn(ResultCode.FAILED_FORBIDDEN .toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_FORBIDDEN ));
        }

        // 构造要更新的对象
        Article updateArticle = new Article();
        updateArticle.setId(article.getId());
        updateArticle.setDeleteState((byte) 1);
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if(row != 1) {
            // ERROR_SERVICES          (2000, "服务器内部错误"),
            log.warn(ResultCode.ERROR_SERVICES.toString());

            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
        //版块帖子数量 -1
        boardService.subOneArticleCountById(article.getBoardId());
        //用户发帖数量 -1
        userService.subOneArticleCountById(article.getUserId());
    }


    @Override
    public void addOneReplyCountById(Long id) {
        //非空校验
        if(id == null || id <= 0) {
            //FAILED_PARAMS_VALIDATE  (1002, "参数校验失败"),
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());

            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 获取帖子详情
        Article article = articleMapper.selectByPrimaryKey(id);
        // 帖子不存在
        if (article == null || article.getDeleteState() == 1) {
            // 打印日志  FAILED_NOT_EXISTS        (1005, "资源不存在"),
            log.warn(ResultCode. FAILED_NOT_EXISTS .toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode. FAILED_NOT_EXISTS ));
        }
        // 帖子状态异常
        if (article.getState() == 1) {
            // 打印日志  FAILED_FORBIDDEN        (1003, "禁止访问"),
            log.warn(ResultCode.FAILED_FORBIDDEN .toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_FORBIDDEN ));
        }

        // 构造要更新的对象
        Article updateArticle = new Article();
        updateArticle.setId(article.getId());
        //回复数 + 1
        updateArticle.setReplyCount(article.getReplyCount() + 1);
        updateArticle.setUpdateTime(new Date());
        //执行更新
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if(row != 1) {
            // ERROR_SERVICES          (2000, "服务器内部错误"),
            log.warn(ResultCode.ERROR_SERVICES.toString());

            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }

    }

    /**
     * 根据UserId查询所有帖子
     * @param userId
     * @return
     */
    @Override
    public List<Article> selectByUserId(Long userId) {
        //非空校验
        if(userId == null || userId <= 0) {
            //FAILED_PARAMS_VALIDATE  (1002, "参数校验失败"),
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());

            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //校验用户是否存在
        User user = userService.selectById(userId);
        if(user == null) {
            //FAILED_USER_NOT_EXISTS  (1102,"用户不存在"),
            log.info(ResultCode.FAILED_USER_NOT_EXISTS.toString());

            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS  ));
        }
        List<Article> articles = articleMapper.selectByUserId(userId);
        return articles;
    }
}
